package com.zhuyuan.security.util;

import com.zhuyuan.security.service.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Author: 张琳凯
 * @Description: Security工具类
 * @DateTime: 2024/12/19 16:18
 **/
public class SecurityUtils {


    /**
     * 获取Authentication
     */
    private static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前用户信息
     */
    public static UserDetailsImpl getCurrentUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetailsImpl){
            return (UserDetailsImpl)principal;
        }
        return null;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        UserDetailsImpl currentUser = getCurrentUser();
        if (currentUser==null){
            return null;
        }
        return currentUser.getUserId();
    }

    /**
     * 获取用户名称
     */
    public static String getUsername() {
        UserDetailsImpl authentication = getCurrentUser();
        return authentication.getUsername();
    }
}
